'use strict';

const wxConfig = {
	appid: 'wx9e5bd19125b4a420', //微信小程序AppId
	appSecret: '7a95975a911dac939db0b0828ac49487', //微信小程序AppSecret
};


//上面的字段非常重要，配置了才能正常进行微信授权登录！！！

const db = uniCloud.database();

async function login(event) {
	let data = {
		appid: wxConfig.appid,
		secret: wxConfig.appSecret,
		js_code: event.code,
		grant_type: 'authorization_code'
	};

	const res = await uniCloud.httpclient.request('https://api.weixin.qq.com/sns/jscode2session', {
		method: 'GET',
		data,
		dataType: 'json'
	});

	const success = res.status === 200 && res.data && res.data.openid;
	if (!success) {
		return {
			code: -1,
			msg: '微信登录失败'
		}
	}

	const {
		openid,
		//session_key 暂不需要session_key
	} = res.data;

	let userInfo = {
		nickName: event.userInfo.nickName,
		avatarUrl: event.userInfo.avatarUrl,
		gender: event.userInfo.gender,
		openid
	};

	const userInDB = await db.collection('user').where({
		openid
	}).get();

	let userUpdateResult;
	if (userInDB.data && userInDB.data.length === 0) {
		userUpdateResult = await db.collection('user').add(userInfo);
	} else {
		// userUpdateResult = await db.collection('user').doc(userInDB.data[0]._id).set(userInfo);
		return {
			code: 0,
			msg: '登录成功',
			data: userInfo
		}
	}

	if (userUpdateResult.id || userUpdateResult.updated === 1) {
		return {
			code: 0,
			msg: '登录成功',
			data: userInfo
		}
	}

	return {
		code: -1,
		msg: '微信登录失败'
	}
}

exports.main = login;
